﻿@{
    Layout = "";
}
<style>
    .ngdialog.ngdialog-theme-plain .ngdialog-content {
        width: 60% !important;
    }
</style>
<h3>{{ (ParentName && ParentName !== '') ? '产品分类-' + ParentName : '产品分类' }}</h3>
<div class="panel panel-default" ng-class="{ 'whirl standard': isLoading,'': isLoading }">
    <div class="panel-heading">
        <div class="form-inline ng-pristine ng-valid">
            <div class="form-group">
                <input placeholder="关键字" class="form-control" type="text" ng-model="Keywords">
                <select ng-model="IsDisplay" class="form-control">
                    <option value="">全部</option>
                    <option value="1">是</option>
                    <option value="2">否</option>
                </select>
                <button type="submit" class="btn btn-labeled btn-primary" ng-click="search(Keywords)">
                    <span class="btn-label">
                        <em class="fa fa-search"></em>
                    </span>搜索
                </button>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-labeled btn-success" ng-click="updateProductCategory(0,ParentId,Message)">
                    <span class="btn-label">
                        <em class="fa fa-plus"></em>
                    </span>新增
                </button>
            </div>
        </div>
    </div>
    <div class="panel-body">
        <div class="table-responsive">
            <table ng-table="tableParams" class="table table-striped table-bproducted table-hover">
                <tbody>
                    <tr ng-repeat="productCategory in $data">
                        <td data-title="'分类名称'" sortable="'CategoryName'" class="text-center">{{productCategory.CategoryName}}</td>
                        <td data-title="'分类图片'" class="text-center">
                            <img ng-src="{{ImgHostUrl + productCategory.PicUrl}}" style="max-width: 25%; max-height: 25%" onerror="javascript: this.src = '/Content/img/default.png';" ng-if="productCategory.PicUrl && productCategory.PicUrl!=''" />
                        </td>
                        <td data-title="'是否显示在分类列表'" class="text-center">{{productCategory.IsDisplay ? '是' : '否'}}</td>
                        <td data-title="'是否热门'" class="text-center" ng-show="ParentId>0">{{productCategory.IsHot ? '是' : '否'}}</td>
                        <td data-title="'排序'" sortable="'DisplayOrder'" class="text-center">{{productCategory.DisplayOrder}}</td>
                        <td data-title="'添加时间'" sortable="'AddTime'" class="text-center">{{productCategory.AddTime}}</td>
                        <td data-title="''" nowrap="nowrap">
                            <button type="button" ng-click="updateProductCategory(productCategory.Id,ParentId,productCategory)" class="btn btn-sm btn-edit" title="编辑">
                                <em class="fa fa-edit"></em>
                            </button>
                            <button type="button" ng-click="secondProductCategory(productCategory.Id)" class="btn btn-sm btn-default" title="二级分类管理" ng-if="productCategory.ParentId == 0">
                                <em class="fa fa-reorder"></em>
                            </button>
                            <button type="button" ng-click="changeState(productCategory)" class="btn btn-sm btn-info" title="{{productCategory.IsHot == true ? '取消热门' : '设为热门'}}"
                                    ng-if="productCategory.ParentId != 0">
                                <em ng-class="{ 'fa fa-toggle-on': productCategory.IsHot == true ,'fa fa-toggle-off': productCategory.IsHot != true }"></em>
                            </button>
                            <button type="button" ng-click="removeProductCategory($index,productCategory)" class="btn btn-sm btn-danger" title="删除">
                                <em class="fa fa-trash-o"></em>
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <input id="fileInput" type="file" style="display: none;" nv-file-select="" uploader="uploader" />
        <input type="hidden" id="uploadFlag" />
    </div>
    <div class="panel-footer text-right">
        <button type="button" class="btn btn-warning" ng-click="returnFirst()" ng-if="ParentId != 0">返回一级分类</button>
    </div>
    <script type="text/ng-template" id="modalDialogId">
        <div class="ngdialog-message text-center">
            <h3>确定要删除吗?</h3>
            <p>删除后不可恢复!</p>
            <br />
            <button type="button" ng-click="confirm()" class="btn btn-primary mr">确认</button>
            <button type="button" ng-click="closeThisDialog('button')" class="btn btn-default">取消</button>
        </div>
    </script>

    <script type="text/ng-template" id="addCategory">
        <div class="ngdialog-message">
            <div class="row">
                <div class="col-md-12">
                    <form class="form-horizontal">
                        <div class="panel panel-default">
                            <div class="panel-body">
                                <fieldset class="b0">
                                    <legend>{{AddProductCategory.Id == 0 || AddProductCategory.Id == null ? '添加' : '修改'}}产品{{AddProductCategory.ParentId == 0?'一级':'二级'}}分类</legend>
                                </fieldset>
                                <fieldset>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">分类名称</label>
                                        <div class="col-sm-2">
                                            <input type="text" ng-model="AddProductCategory.CategoryName" class="form-control" maxlength="10" />

                                        </div>
                                        <div class="col-sm-4">
                                            <h4 class="text-danger" style="color:red">*</h4>
                                        </div>
                                    </div>
                                </fieldset>
                                <fieldset>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">分类图片</label>
                                        <div class="col-sm-3">
                                            <div class="imgcrop-preview" uploader="uploader">
                                                <img ng-src="{{myCroppedImage}}" style="max-width: 100%; max-height: 100%" onerror="javascript: this.src = '/Content/img/default.png';" />

                                            </div>
                                            <div>
                                                <div style="" class="progress progress-xs" ng-show="uploading">
                                                    <div role="progressbar" ng-style="{ 'width': uploader.progress + '%' }" class="progress-bar"></div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-5">
                                            <button type="button" class="mb-sm btn btn-info" ng-click="selectImage()">
                                                图片选择
                                            </button>
                                            <span class="text-danger">建议尺寸：320x320</span>
                                        </div>
                                    </div>
                                </fieldset>
                                <fieldset>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">
                                            排序
                                            <a href="javascript:void(1)" class="lml_sample">
                                                <i class="ico_help">?</i>
                                                <span class="help_pop" display="inline-block" style="width: 220px; text-align: left;left:-100px">
                                                    排序设置的数值越大，分类越靠前。
                                                </span>
                                            </a>
                                        </label>
                                        <div class="col-sm-2">
                                            <input class="form-control" type="number" maxlength="5" ng-model="AddProductCategory.DisplayOrder">
                                        </div>
                                    </div>
                                </fieldset>
                                <fieldset>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">是否显示在分类列表</label>
                                        <div class="col-sm-2">
                                            <label class="radio-inline c-radio">
                                                <input type="radio" required="" name="isDisplay" ng-value="{{true}}" ng-model="AddProductCategory.IsDisplay" />
                                                <span class="fa fa-circle"></span>是
                                            </label>
                                            <label class="radio-inline c-radio">
                                                <input type="radio" required="" name="isDisplay" ng-value="{{false}}" ng-model="AddProductCategory.IsDisplay" />
                                                <span class="fa fa-circle"></span>否
                                            </label>
                                        </div>
                                        <div class="col-sm-4">
                                            <h4 class="text-danger" style="color:red">*</h4>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label"></label>
                                        <div class="col-sm-6">
                                            <div ng-show="validateInput('isDisplay', 'required')" class="text-danger form-control-static">请选择是否显示在分类列表</div>
                                        </div>
                                    </div>
                                </fieldset>
                                <fieldset ng-if="AddProductCategory.ParentId == 0">
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">广告图片</label>
                                        <div class="col-sm-3">
                                            <div class="imgcrop-preview" uploader="uploader">
                                                <img ng-src="{{myCroppedImage2}}" style="max-width: 100%; max-height: 100%" onerror="javascript: this.src = '/Content/img/default.png';" />

                                            </div>
                                        </div>
                                        <div class="col-sm-5">
                                            <button type="button" class="mb-sm btn btn-info" ng-click="selectImageAD()">
                                                图片选择
                                            </button>
                                            <button type="button" class="mb-sm btn btn-green" ng-click="clearImage()">
                                                清空
                                            </button>
                                            <span class="text-danger">建议尺寸：320x80</span>
                                        </div>
                                    </div>
                                </fieldset>
                                <fieldset ng-if="AddProductCategory.ParentId == 0">
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">
                                            广告位链接
                                        </label>
                                        <div class="col-sm-6">
                                            <input class="form-control" type="text" maxlength="200" ng-model="AddProductCategory.ADUrl">
                                        </div>
                                    </div>
                                </fieldset>
                            </div>
                            <div class="panel-footer text-right">
                                <button type="button" class="btn btn-default" ng-click="closeDialog()">
                                    关闭
                                </button>
                                <button type="button" class="btn btn-default" ng-click="serveThisMessage()">
                                    确定
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </script>
</div>
<script>
    App.controller('ProductCategoryController', [
    '$scope', '$rootScope', '$resource', '$state', '$route', 'ngDialog', '$http', 'ngTableParams', 'ngTableDataService', 'Notify', '$stateParams', "FileUploader",
    function ($scope, $rootScope, $resource, $state, $route, ngDialog, $http, ngTableParams, ngTableDataService, Notify, $stateParams, FileUploader) {
        'use strict';
        $scope.isLoading = true;
        $scope.ParentId = $stateParams.ParentId;
        $scope.Message = {};
        $scope.tabHeadName = '一级分类';
        $scope.tableParams = new ngTableParams({
            page: 1,
            count: 10,
            sorting: {
                AddTime: 'desc'     // 初始化排序
            }
        }, {
            getData: function ($defer, params) {
                $scope.isLoading = true;
                var requestParams = {
                    Skip: (params.page() - 1) * params.count(),
                    Take: params.count(),
                    Keywords: $scope.Keywords,
                    ParentId: $scope.ParentId,
                    IsDisplayParm: $scope.IsDisplay
                };
                $http.post('/ProductCategory/ProductCategoryManage', ngTableDataService.getServerSideParams(params.orderBy().toString(), params, requestParams))
                    .success(function (data, status) {
                        params.total(data.Total);
                        $defer.resolve(data.Results);
                        $scope.ParentName = data.ParentName;
                        $scope.isLoading = false;
                    });
            }
        });
        //查询
        $scope.search = function (keyword) {
            $scope.Keywords = keyword;
            $scope.tableParams.$params.page = 1;
            $scope.tableParams.reload();
        }
        //查看二级分类
        $scope.secondProductCategory = function (id, name) {
            $scope.Keywords = '';
            $scope.ParentId = id;
            $scope.ParentName = name;
            $scope.tableParams.$params.page = 1;
            $scope.tableParams.reload();
        }

        //返回一级分类
        $scope.returnFirst = function () {
            $scope.Keywords = '';
            $scope.ParentId = 0;
            $scope.ParentName = '';
            $scope.tableParams.$params.page = 1;
            $scope.tableParams.reload();
        }


        //设为热门
        $scope.changeState = function (productcategory) {

            $http.post("/ProductCategory/ChangeCategoryState", { Id: productcategory.Id }).then(function (returnData) {
                productcategory.IsHot = returnData.data.Hot;
                Notify.alert('操作成功!', { status: 'success', timeout: 1000 });

            });
        }
        //$scope.updateProductCategory = function (id, parentId) {
        //    $state.go('app.updateProductCategoryView', { Id: id, ParentId: parentId });
        //}

        //跳转更新新增页面
        $scope.updateProductCategory = function (id, parentId, productcategory) {
            $scope.getTempId = id;
            $scope.getTempParentId = parentId;
            if (id == 0) {
                $scope.AddProductCategory = {
                    IsDisplay: 1,
                    ParentId: parentId,
                    Id: id
                };
            } else {
                $scope.AddProductCategory = angular.copy(productcategory);
                if ($scope.AddProductCategory.PicUrl && $scope.AddProductCategory.PicUrl != '') {
                    $scope.myCroppedImage = $rootScope.ImgHostUrl + angular.copy($scope.AddProductCategory.PicUrl);
                }
                if ($scope.AddProductCategory.ADPicUrl && $scope.AddProductCategory.ADPicUrl != '') {
                    $scope.myCroppedImage2 = $rootScope.ImgHostUrl + angular.copy($scope.AddProductCategory.ADPicUrl);
                }

            }


            ngDialog.openConfirm({
                template: 'addCategory',
                className: 'ngdialog-theme-plain',
                scope: $scope,
                preCloseCallback: function () {
                    $scope.myCroppedImage = undefined;
                    $scope.myCroppedImage2 = undefined;
                    return true;
                }
            }).then(function (value) {
            }, function (reason) {
            }
            );
        }
        //清空图片
        $scope.clearImage = function () {
            $scope.myCroppedImage2 = undefined;
            $scope.AddProductCategory.ADPicUrl = '';
        }

        //点击确认保存
        $scope.serveThisMessage = function () {
            if ($scope.AddProductCategory.CategoryName == null || $scope.AddProductCategory.CategoryName.length <= 0) {
                Notify.alert('请输入分类名称!', { status: 'warning', timeout: 1000 });
                $scope.isLoading = false;
                return false;
            }
            //var isRightNum = /^[0-9]{1}[\d]*$/.test($scope.AddProductCategory.DisplayOrder);
            //if ($scope.AddProductCategory.DisplayOrder != null && isRightNum == false) {
            //    Notify.alert('请输入正确排序!', { status: 'warning', timeout: 1000 });
            //    $scope.isLoading = false;
            //    return false;
            //}
            if ($scope.AddProductCategory.PicUrl == null || $scope.AddProductCategory.PicUrl.length <= 0) {
                Notify.alert('请上传分类图片!', { status: 'warning', timeout: 1000 });
                $scope.isLoading = false;
                return false;
            }

            $http.post("/ProductCategory/UpdateCategory", $scope.AddProductCategory).then(function (returnData) {
                if (returnData.data.isSuccess) {
                    Notify.alert('操作成功!', { status: 'success', timeout: 1000 });
                    ngDialog.closeAll();
                    if ($scope.getTempParentId > 0) {
                        $scope.Keywords = '';
                        $scope.ParentId = $scope.getTempParentId;
                        $scope.ParentName = name;
                        $scope.tableParams.$params.page = 1;
                        $scope.tableParams.reload();
                    } else {
                        $scope.Keywords = '';
                        $scope.ParentId = 0;
                        $scope.ParentName = '';
                        $scope.tableParams.$params.page = 1;
                        $scope.tableParams.reload();
                    }
                    $scope.myCroppedImage = undefined;
                    // $state.go("app.productCategory", { ParentId: $scope.ProductCategory.ParentId });
                } else {
                    Notify.alert(returnData.data.msg, { status: 'warning', timeout: 1000 });
                }
            });
        }
        //点击关闭
        $scope.closeDialog = function () {
            ngDialog.closeAll();
            $scope.myCroppedImage = undefined;
        }

        //删除
        $scope.removeProductCategory = function (index, productCategory) {
            ngDialog.openConfirm({
                template: 'modalDialogId',
                className: 'ngdialog-theme-default'
            }).then(function (value) {
                $http.post("/ProductCategory/DelCategory", { Id: productCategory.Id }).then(function (returnData) {
                    if (returnData.data.isSuccess) {
                        $scope.tableParams.data.splice(index, 1);
                        Notify.alert('操作成功!', { status: 'success', timeout: 1000 });
                    } else {
                        Notify.alert(returnData.data.msg, { status: 'warning', timeout: 1000 });
                    }
                });
            }, function (reason) {
            }
            );
        }
        //-------------图片选择相关
        $scope.selectImage = function () {
            $("#uploadFlag").val(0);
            $("#fileInput").click();
        }
        $scope.selectImageAD = function () {
            $("#uploadFlag").val(1);
            $("#fileInput").click();
        }

        var handleFileSelect = function (evt) {
            var file = $scope.uploadSelectFile = evt.currentTarget.files[0];
            if (!evt.currentTarget.files[0] || ! /image\/\w+/.test(evt.currentTarget.files[0].type)) {
                Notify.alert('请选择图像文件', { status: 'warning' });
                return false;
            }
            if (file.size > 1 * 1024 * 1024) {
                Notify.alert('图片大小不能大于1MB', { status: 'warning', timeout: 3000 });
                $scope.uploadSelectFile = null;
                return false;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                $scope.$apply(function ($scope) {
                    if ($("#uploadFlag").val() == 0) {
                        $scope.myCroppedImage = evt.target.result;
                    } else {
                        $scope.myCroppedImage2 = evt.target.result;
                    }
                });
            };
            if (file)
                reader.readAsDataURL(file);
        };

        angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
        var uploader = $scope.uploader = new FileUploader({
            url: $rootScope.ImgUploadUrl + '?PlatForm=wsd&Path=ProductCategory'
        });
        uploader.filters.push({
            name: 'customFilter',
            fn: function (item /*{File|FileLikeObject}*/, options) {
                return true;
            }
        });

        // CALLBACKS

        uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
            //  console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfterAddingFile = function (fileItem) {
            if ($scope.uploadSelectFile && /image\/\w+/.test($scope.uploadSelectFile.type)) {
                $scope.uploading = true;
                fileItem.upload();
            }
            //    console.info('onAfterAddingFile', fileItem);
        };
        uploader.onAfterAddingAll = function (addedFileItems) {
            //   console.info('onAfterAddingAll', addedFileItems);
        };
        uploader.onBeforeUploadItem = function (item) {
            // console.info('onBeforeUploadItem', item);
        };
        uploader.onProgressItem = function (fileItem, progress) {
            // console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function (progress) {
            //  console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function (fileItem, response, status, headers) {
            console.log(response[0]);
            if ($("#uploadFlag").val() == 0) {
                $scope.AddProductCategory.PicUrl = response[0];
            } else {
                $scope.AddProductCategory.ADPicUrl = response[0];
            }
            
            $("#fileInput").val("");
            //  console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function (fileItem, response, status, headers) {
            //  console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function (fileItem, response, status, headers) {
            // console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function (fileItem, response, status, headers) {
            //  console.info('onCompleteItem', fileItem, response, status, headers);
        };
        uploader.onCompleteAll = function () {
            $scope.uploading = false;
        };

    }]);
</script>